#!/bin/sh


user="kuang"
host="120.78.154.52"
upload_path="/home/kuang"
target_path="/home/kuang/kuang"
log_path="/home/kuang/log/kuang/"
image_name="wx-youhui"
con_name="you"
con_port="8888"
host_port="8080"

# user="youhuigo"
# host="118.31.14.157"
# upload_path="/home/youhuigo"
# target_path="/home/youhuigo/youhuigo"
# log_path="/home/youhuigo/log/youhuigo/"
# image_name="wx-youhui"
# con_name="youhui"
# con_port="8888"
# host_port="8888"



# user="kuang"
# host="120.25.203.47"
# upload_path="/home/kuang"
# target_path="/home/kuang/youhuigo"
# log_path="/home/kuang/log/kuang/"
# image_name="wx-youhui"
# con_name="youhui"
# con_port="8888"
# host_port="8888"


# 以上是配置参数变量
# 公共变量
version=$1
build=$2
first=$3
ssh_login='ssh '$user'@'$host


if [ $version = "-h" ]; then
	echo '脚本参数： \n    <version> <build> <status>'
	echo '    build: \n\t缺省或不为-b立即构建war \n\t-b：不进行构建'
	echo '    status: \n\t缺省或任意则更新一个版本 \n\t-f: 第一次创建容器运行'
	exit 0
fi

if [ "$build"x != "-b"x ]; then
	gradle war
	gradle bootRepackage 
fi

# 文件上传并处理
scp build/libs/weixin*.war $user@$host:$upload_path
$ssh_login 'rm -rf '$target_path'/*.war \'
$ssh_login 'mv '$upload_path'/*.war '$target_path'/ \'

# 进行构建镜像
$ssh_login 'cd '$target_path' \
	 && echo -e "FROM frolvlad/alpine-oraclejdk8:slim" > Dockerfile \
     && echo -e "ADD weixin-*.war app.war" >> Dockerfile \
     && echo -e "ENTRYPOINT [\"java\",\"-jar\",\"/app.war\"]" >> Dockerfile \
     && docker build -t '$image_name':'$version' . \'

# 如果是第一次，就要创建dockerfile，否则只要删除旧容器即可
if [ "$first"x != "-f"x ]; then
	$ssh_login 'docker rm -f '$con_name
	# 删除成功会在控制台输出容器名
fi

$ssh_login 'docker run --name '$con_name' -d -p '$host_port':'$con_port' -e TZ=Asia/Shanghai -v '$log_path':/logs' $image_name':'$version''

gradle --stop


echo 'docker run --name '$con_name' -d -p '$host_port':'$con_port' -e TZ=Asia/Shanghai -v '$log_path':/logs' $image_name':'$version''
